Imports System.IO
Imports System.Diagnostics
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports Microsoft.VisualBasic

Imports System
Imports System.Runtime.InteropServices
Imports System.Net



Partial Class reports
  Inherits System.Web.UI.Page

  Dim PerlsDir As String = ConfigurationManager.AppSettings("PerlsDirectory")
  Dim ReportsDir As String = Server.MapPath(ConfigurationManager.AppSettings("AvsReports"))
  Dim PublishDir As String = ConfigurationManager.AppSettings("PublishDirectory")

  Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRun.Click
    ' executes perl based on slected parameters

    ' clear the list box
    Response.Buffer = False
    Response.BufferOutput = False

    ' Create the ProcessInfo object
    Dim psi As New ProcessStartInfo("cmd.exe")
    psi.UseShellExecute = False
    psi.RedirectStandardOutput = True
    psi.RedirectStandardInput = True
    psi.RedirectStandardError = True

    ' Start the process
    Dim proc As Process = Process.Start(psi)
    ' capture outputs async
    AddHandler proc.OutputDataReceived, AddressOf ProcessOutputHandler
    AddHandler proc.ErrorDataReceived, AddressOf ProcessOutputHandler

    ' write the commands to the process
    Dim sw As StreamWriter = proc.StandardInput
    sw.WriteLine(PerlsDir.Substring(0, 2))
    sw.WriteLine("cd " & PerlsDir)
    sw.WriteLine("perl " & ddlReports.SelectedValue & " " & ddlDate.SelectedValue & " " & ddlColleges.SelectedValue)
    sw.WriteLine("exit")

    ' display whatever comes back.
    proc.BeginOutputReadLine()
    proc.BeginErrorReadLine()
    proc.WaitForExit()

    proc.Close()
    sw.Close()

    build_datalist1()

  End Sub
  Protected Sub ProcessOutputHandler(ByVal sendingProcess As Object, _
  ByVal outLine As DataReceivedEventArgs)
    If Not String.IsNullOrEmpty(outLine.Data) Then
      '      ListBox1.Items.Add(outLine.Data & vbCrLf)
      Response.Write(outLine.Data & "<br>")
      Response.Flush()
    End If
  End Sub
  Protected Sub ddlDate_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlDate.Init
    ' find last day of this month
    Dim myDate As New Date(Today().Year, Today().Month, Today().AddMonths(1).AddDays(-1).Day)
    Dim i As Integer
    '  put previous 24 months in drop down
    For i = 0 To 24
      myDate = myDate.AddMonths(-1)
      ddlDate.Items.Insert(i, New ListItem(myDate.Month & "-" & myDate.Year, myDate.Year & "-" & myDate.Month & "-1"))
    Next
  End Sub

  Protected Sub ddlColleges_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlColleges.DataBound
    ddlColleges.Items.Insert(0, New ListItem("All Colleges", 0))
  End Sub

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If (Not Page.IsPostBack) Then
      build_datalist1()
    End If
  End Sub

  Protected Sub build_datalist1()
    ' plop directory of files on the screen
    Dim dirInfo As DirectoryInfo = New DirectoryInfo(ReportsDir)
    DataList1.DataSource = dirInfo.GetFiles()
    DataList1.DataBind()
    ListBox2.DataSource = dirInfo.GetFiles()
    ListBox2.DataBind()
  End Sub
  Protected Sub btnPublish_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPublish.Click
    ' copy selected files their final resting place and remove from the reports directory
    Dim listitem As ListItem
    Dim report As String

    ' found on the internet, makes network share connection and allows copy
    Dim nr As NETRESOURCE() = New NETRESOURCE(0) {}
    nr(0).lpRemoteName = PublishDir
    nr(0).lpLocalName = ""
    'mLocalName;
    nr(0).dwType = 1
    'disk
    nr(0).dwDisplayType = 0
    nr(0).dwScope = 0
    nr(0).dwUsage = 0
    nr(0).lpComment = ""
    nr(0).lpProvider = ""
    WNetAddConnection2A(nr, ConfigurationManager.AppSettings("PublishPassword"), ConfigurationManager.AppSettings("PublishUser"), 0)

    For Each listitem In ListBox2.Items
      If listitem.Selected Then
        report = listitem.Text.ToString
        If report.Substring(7, 3) = "ALL" Then
          CopyStatewideReports(report)
        Else
          File.Copy(ReportsDir & report, PublishDir & "\" & report, True)
        End If
        File.Delete(ReportsDir & report)
      End If
    Next

    WNetCancelConnection2A(PublishDir, 0, -1)

    build_datalist1()
  End Sub
  Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
    Dim listitem As ListItem
    For Each listitem In ListBox2.Items
      If listitem.Selected Then
        File.Delete(ReportsDir & listitem.Text)
      End If
    Next
    build_datalist1()
  End Sub

  Protected Sub CopyStatewideReports(ByVal report As String)
    ' if the aleph code is all, publish a copy for each college
    ' have to read through the colleges table
    Dim mySqlConnection As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("VendorStatsConnectionString").ToString)
    Dim mySqlCommand As New SqlCommand
    Dim mySqlDataReader As SqlDataReader
    mySqlConnection.Open()

    mySqlCommand.CommandType = CommandType.Text
    mySqlCommand.Connection = mySqlConnection
    mySqlCommand.CommandText = "SELECT Aleph FROM Colleges"
    mySqlDataReader = mySqlCommand.ExecuteReader()
    While mySqlDataReader.Read()
      File.Copy(ReportsDir & report, PublishDir & "\" & report.Replace("ALL", mySqlDataReader.GetString(0)), True)
    End While
    mySqlDataReader.Close()
    mySqlConnection.Close()
  End Sub


  'used in calling WNetAddConnection2
  <StructLayout(LayoutKind.Sequential)> _
  Public Structure NETRESOURCE
    Public dwScope As Integer
    Public dwType As Integer
    Public dwDisplayType As Integer
    Public dwUsage As Integer
    <MarshalAs(UnmanagedType.LPStr)> _
    Public lpLocalName As String
    <MarshalAs(UnmanagedType.LPStr)> _
    Public lpRemoteName As String
    <MarshalAs(UnmanagedType.LPStr)> _
    Public lpComment As String
    <MarshalAs(UnmanagedType.LPStr)> _
    Public lpProvider As String
  End Structure

  'WIN32API - WNetAddConnection2
  <DllImport("mpr.dll", CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _
  Private Shared Function WNetAddConnection2A(<MarshalAs(UnmanagedType.LPArray)> ByVal lpNetResource As NETRESOURCE(), <MarshalAs(UnmanagedType.LPStr)> ByVal lpPassword As String, <MarshalAs(UnmanagedType.LPStr)> ByVal lpUserName As String, ByVal dwFlags As Integer) As Integer
  End Function

  'WIN32API - WNetCancelConnection2
  <DllImport("mpr.dll", CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _
  Private Shared Function WNetCancelConnection2A(<MarshalAs(UnmanagedType.LPStr)> ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Integer) As Integer
  End Function

  'Public Shared Sub CopyFile(ByVal share As String, ByVal username As String, ByVal password As String, ByVal dirFrom As String, ByVal dirTo As String, ByVal filename As String)
  '  Dim nr As NETRESOURCE() = New NETRESOURCE(0) {}
  '  nr(0).lpRemoteName = share
  '  nr(0).lpLocalName = ""
  '  'mLocalName;
  '  nr(0).dwType = 1
  '  'disk
  '  nr(0).dwDisplayType = 0
  '  nr(0).dwScope = 0
  '  nr(0).dwUsage = 0
  '  nr(0).lpComment = ""
  '  nr(0).lpProvider = ""
  '  WNetAddConnection2A(nr, password, username, 0)

  '  File.Copy(dirFrom + "\" + filename, dirTo + "\" + filename)

  '  WNetCancelConnection2A(share, 0, -1)
  'End Sub

End Class